package com.xiaoshuidi.cloud.module.system.service.oos;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xiaoshuidi.cloud.framework.oss.config.OosFileClientConfig;
import com.xiaoshuidi.cloud.module.system.controller.admin.oss.config.OosClientConfig;
import com.xiaoshuidi.cloud.module.system.dal.dataobject.oos.SystemImageDO;
import com.xiaoshuidi.cloud.module.system.dal.mysql.oos.SystemImageMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * oos Service 实现类
 *
 * @author
 */
@Service
@Slf4j
public class OosServiceImpl implements OosService {

    @Resource
    private AmazonS3 ossClient;
    @Resource
    private OosClientConfig oosClientConfig;
    @Resource
    private SystemImageMapper systemImageMapper;

    @Override
    public Map<String, Object> uploadFile(MultipartFile file, String fileName) {
        String pathUrl;
        try (InputStream inputStream = file.getInputStream()) {
            String remoteFilePath = DateUtil.format(new Date(), "yyyy-MM-dd");
            String dir = remoteFilePath + "/"; // 用户上传文件时指定的前缀。
            // 创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            String path = dir + IdWorker.getIdStr() + suffix;

            HashMap<String, Object> result = new HashMap<>();
            try {
                objectMetadata.setContentLength(inputStream.available());
                // 上传文件
                log.info("开始上传文件到oss bucket: {} path: {}", oosClientConfig.getBucket(), path);
                ossClient.putObject(oosClientConfig.getBucket(), path, inputStream, objectMetadata);
                String url = generatePresignedUrl(path);
                log.info("oss文件下载链接 url: {}", url);
                pathUrl = url.substring(0, url.indexOf("?"));
                // 中建东孚需要替换域名
                if (StringUtils.isNotBlank(oosClientConfig.getSubUrl())){
                    pathUrl = pathUrl.replace("http://"+oosClientConfig.getEndpoint(),oosClientConfig.getSubUrl());
                }
                SystemImageDO systemImageDO = new SystemImageDO().setUrl(pathUrl);
                switch (suffix){
                    case ".jpg":
                    case ".gif":
                    case ".tif":
                    case ".jpeg":
                    case ".bmp":
                        systemImageMapper.insert(systemImageDO.setType("1"));
                        break;
                    case ".mp4":
                    case ".rmvb":
                    case ".rm":
                    case ".asf":
                    case ".divx":
                    case ".mpg":
                    case ".mpeg":
                    case ".wmv":
                    case ".mkv":
                    case ".vob":
                        systemImageMapper.insert(systemImageDO.setType("2"));
                        break;
                    default:
                        systemImageMapper.insert(systemImageDO.setType("3"));
                }

                result.put("pathUrl" ,pathUrl);
                result.put("id" ,systemImageDO.getId());
            } catch (Exception e) {
                log.error("上传文件到oos失败", e);
            }
            return result;
        } catch (Exception e) {
            log.error("", e);
        }
        return null;
    }

    @Override
    public InputStream oosDownloadFile(String url) {
        byte[] bytes1 = HttpUtil.downloadBytes(url);
        return new ByteArrayInputStream(bytes1);
        /*AmazonS3 oosClient = this.oosClientConfig.oosClient();
        String head = oosClientConfig.getSubUrl() + "/";
        String path = url.replace(head, "");
        S3Object object = oosClient.getObject(this.oosClientConfig.getBucket(), path);
        S3ObjectInputStream InputStream = object.getObjectContent();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        byte[] bytes;
        try {
            bytes = new byte[1024];

            int len;
            while((len = InputStream.read(bytes)) != -1) {
                baos.write(bytes, 0, len);
            }
        } catch (IOException var19) {
            var19.printStackTrace();
        } finally {
            try {
                if (InputStream != null) {
                    InputStream.close();
                }
            } catch (IOException var18) {
                var18.printStackTrace();
            }

        }

        bytes = baos.toByteArray();
        return new ByteArrayInputStream(bytes);*/
    }


    /**
     * @Desecription: 获取文件下载地址
     */
    @Override
    public String generatePresignedUrl(String fileKey) {
        GeneratePresignedUrlRequest request = new
                GeneratePresignedUrlRequest(oosClientConfig.getBucket(), fileKey);
        URL url = ossClient.generatePresignedUrl(request);
        return url.toString();
    }
}
